<script lang="ts" setup>
import {onMounted, reactive, ref, type UnwrapRef} from 'vue';
import dayjs, {Dayjs} from "dayjs";
import {getJobDetailAndEmployerByJobIdAPI,} from "@/apis/job.ts";
import {useRoute} from "vue-router";
import {addCollectAPI, deleteCollectAPI, getCollectByJobEmployerIdAPI} from "@/apis/collect.ts";
import {useInfoStore} from "@/store/user/user.ts";
import {message, type UploadChangeParam} from "ant-design-vue";
import {addSendAPI, deleteSendAPI, isSendJobAPI} from "@/apis/send.ts";
import router from "@/router";
import {InboxOutlined} from "@ant-design/icons-vue";
import type {Rule} from "ant-design-vue/es/form";
import {addReportAPI} from "@/apis/report.ts";

//表单数据
interface FormState {
  jobId: string;
  jobStatus: string;
  jobEmployerId: string;
  jobTitle: string;
  jobType: string;
  jobSalary: string;
  jobSalaryType: string;
  jobGiveStartDate: string;
  jobGiveEndDate: string;
  jobStartDate: string;
  jobEndDate: string;
  jobWorkingHours: string;
  jobDescription: string;
  jobRequirements: string;
  jobLocation: string;
  rangeValue: [Dayjs | null, Dayjs | null];
  rangeValue2: [Dayjs | null, Dayjs | null];

  employerIsVerified: string,
  employerStatus: string,
  employerCompanyName: string,
  userAvatarUrl: string,
  employerCompanyIndustry: string,
  employerCompanyAddress: string,
  employerCompanyDescription: string,
  employerCompanyWebsite: string
}

const formState: UnwrapRef<FormState> = reactive({
  jobId: '',
  jobStatus: '',
  jobEmployerId: '',
  jobTitle: '',
  jobType: '',
  jobSalary: '',
  jobSalaryType: '',
  jobStartDate: '',
  jobEndDate: '',
  jobGiveStartDate: '',
  jobGiveEndDate: '',
  jobWorkingHours: '',
  jobDescription: '',
  jobRequirements: '',
  jobLocation: '',
  rangeValue: [null, null],
  rangeValue2: [null, null],

  employerIsVerified: '',
  employerStatus: '',
  employerCompanyName: '',
  userAvatarUrl: '',
  employerCompanyIndustry: '',
  employerCompanyAddress: '',
  employerCompanyDescription: '',
  employerCompanyWebsite: ''
});


//接收参数
const route = useRoute();
//生命周期
onMounted(() => {
  formState.jobId = route.params.jobId as string;
  getJobInfo()
})
//获取岗位信息
const getJobInfo = async () => {
  if (formState.jobId) {
    const res = await getJobDetailAndEmployerByJobIdAPI(formState.jobId)
    if (res.data.flag) {
      if (res.data.data.jobStatus === '停止招聘') {
        message.error('该岗位已停止招聘')
        setTimeout(() => {
          router.go(-1);
        }, 1000);
      }
      if (res.data.data.jobAdminStatus === '封禁') {
        message.error('该岗位已被封禁')
        setTimeout(() => {
          router.go(-1);
        }, 1000);
      }


      formState.jobStatus = res.data.data.jobStatus
      formState.jobEmployerId = res.data.data.jobEmployerId
      formState.jobTitle = res.data.data.jobTitle
      formState.jobType = res.data.data.jobType
      formState.jobSalary = res.data.data.jobSalary
      formState.jobSalaryType = res.data.data.jobSalaryType
      formState.jobWorkingHours = res.data.data.jobWorkingHours
      formState.jobDescription = res.data.data.jobDescription
      formState.jobRequirements = res.data.data.jobRequirements
      formState.jobLocation = res.data.data.jobLocation
      formState.jobGiveStartDate = dayjs(res.data.data.jobGiveStartDate).format('YYYY-MM-DD')
      formState.jobGiveEndDate = dayjs(res.data.data.jobGiveEndDate).format('YYYY-MM-DD')
      formState.jobStartDate = dayjs(res.data.data.jobStartDate).format('YYYY-MM-DD')
      formState.jobEndDate = dayjs(res.data.data.jobEndDate).format('YYYY-MM-DD')
      // 处理工作周期数据回显
      formState.rangeValue = [
        dayjs(res.data.data.jobGiveStartDate),
        dayjs(res.data.data.jobGiveEndDate)
      ];
      formState.rangeValue2 = [
        dayjs(res.data.data.jobStartDate),
        dayjs(res.data.data.jobEndDate)
      ];

      formState.employerCompanyName = res.data.data.employerCompanyName
      formState.userAvatarUrl = res.data.data.userAvatarUrl
      formState.employerCompanyIndustry = res.data.data.employerCompanyIndustry
      formState.employerCompanyAddress = res.data.data.employerCompanyAddress
      formState.employerCompanyDescription = res.data.data.employerCompanyDescription
      formState.employerCompanyWebsite = res.data.data.employerCompanyWebsite
      formState.employerIsVerified = res.data.data.employerIsVerified
      formState.employerStatus = res.data.data.employerStatus

      await checkCollectAndSend()
    }
  }
}

//查询收藏和投递
const userStore = useInfoStore().userInfo;
const jobIsCollect = ref(false)//岗位是否收藏
const employerIsCollect = ref(false)//企业是否收藏
const jobIsSend = ref(false)//岗位是否投递
const sendId = ref('');//投递id
const checkCollectAndSend = async () => {
  getCollectByJobEmployerIdAPI({
    collectJobseekerId: userStore.userId,
    collectType: 'job',
    collectJobEmployerId: formState.jobId
  }).then((res1) => {
    if (res1.data.flag) {
      jobIsCollect.value = res1.data.data
    } else {
      message.error(res1.data.message)
    }
  })

  getCollectByJobEmployerIdAPI({
    collectJobseekerId: userStore.userId,
    collectType: 'employer',
    collectJobEmployerId: formState.jobEmployerId
  }).then((res2) => {
    if (res2.data.flag) {
      employerIsCollect.value = res2.data.data
    } else {
      message.error(res2.data.message)
    }
  })

  isSendJobAPI({
    sendJobseekerId: userStore.userId,
    sendJobEmployerId: formState.jobEmployerId,
    sendJobId: formState.jobId
  }).then((res3) => {
    if (res3.data.data != 0) {
      jobIsSend.value = true
      sendId.value = res3.data.data
    } else {
      jobIsSend.value = false
    }
  })
}
//收藏岗位
// 获取路由实例
const collect = (JobEmployerId: string, collectType: string) => {
  addCollectAPI({
    collectJobseekerId: userStore.userId,
    collectType: collectType,
    collectJobEmployerId: JobEmployerId
  }).then((res) => {
    if (res.data.flag) {
      message.success(res.data.message)
      checkCollectAndSend()
    } else {
      message.error(res.data.message)
    }
  })
}
//取消收藏
const cancelCollect = (JobEmployerId: string, collectType: string) => {
  deleteCollectAPI({
    collectJobseekerId: userStore.userId,
    collectType: collectType,
    collectJobEmployerId: JobEmployerId
  }).then((res) => {
    if (res.data.flag) {
      message.success(res.data.message)
      checkCollectAndSend()
    } else {
      message.error(res.data.message)
    }
  })
}
//投递岗位
const sendJob = () => {
  addSendAPI({
    sendJobseekerId: userStore.userId,//求职者id
    sendJobEmployerId: formState.jobEmployerId,//企业id
    sendStatus: '已投递',
    sendJobId: formState.jobId,
  }).then((res) => {
    if (res.data.flag) {
      message.success(res.data.message)
      checkCollectAndSend()
    } else {
      message.error(res.data.message)
    }
  })
}
//取消投递
const cancelSendJob = () => {
  deleteSendAPI({
    sendId: sendId.value,
  }).then((res) => {
    if (res.data.flag) {
      message.success(res.data.message)
      checkCollectAndSend()
    } else {
      message.error(res.data.message)
    }
  })
}

//计算颜色
const Color = (colorType: string) => {
  switch (colorType) {
    case '已认证':
      return 'green';
    case '未认证':
      return 'red';
  }
}

//举报弹窗
const labelCol = {span: 5};
const wrapperCol = {span: 13};
const openReport = ref<boolean>(false);

const showModalVerification = () => {
  openReport.value = true;
};

const handleOkVerification = (e: MouseEvent) => {
  console.log("提交了" + e);
  formRefReport.value
      .validate()
      .then(async () => {
        openReport.value = false;
        //循环加入文件url
        formStateReport.reportFileList = fileListReport.value.map((file: any) => {
          return file.response.data;
        });
        addReportAPI({
          reportCheckStatus: '审核中',
          reportUserId: userStore.userId,
          reportUserRole: 'jobseeker',
          reportUsername: userStore.userName,
          reportAccount: userStore.account,
          reportContact: formStateReport.reportContact,//举报人联系方式
          reportObjectId: formState.jobEmployerId, //被举报对象id
          reportObject: formStateReport.reportObject,
          reportDescribe: formStateReport.reportDescribe,
          reportFileList: formStateReport.reportFileList,//上传的文件列表
        }).then((res: any) => {
          if (res.data.flag) {
            message.success('提交成功');
          } else {
            message.error('提交失败');
          }
        })
      })
      .catch(() => {
        console.log("验证失败");
      });
};

interface FormStateReport {
  reportFileList: string[];
  reportDescribe: string;
  reportObject: string;
  reportContact: string;
}

const formRefReport = ref();
const rules: Record<string, Rule[]> = {
  reportObject: [
    {required: true, message: '请选择举报类型', trigger: 'blur',},
  ],
  reportContact: [
    {required: true, message: '请输入联系方式', trigger: 'blur',},
  ],
  reportDescribe: [
    {required: true, message: '请输入举报描述', trigger: 'blur',},
  ],
}
const formStateReport = reactive<FormStateReport>({
  reportFileList: [], //上传的文件列表
  reportDescribe: '',
  reportObject: '',
  reportContact: '',
})

const fileListReport = ref([]);
const handleChangeReport = (info: UploadChangeParam) => {
  const status = info.file.status;
  if (status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (status === 'done') {
    message.success(`${info.file.name} file uploaded successfully.`);
    console.log("url:" + fileListReport.value[0].response.data);
  } else if (status === 'error') {
    message.error(`${info.file.name} file upload failed.`);
  }
};

function handleRemove(e: DragEvent) {
  console.log('删除了', e.response.data);
}

</script>
<template>
  <!--          举报弹窗-->
  <div>
    <a-modal v-model:open="openReport"
             cancel-text="取消-举报"
             ok-text="确认-提交举报"
             title="举报-投诉"
             @ok="handleOkVerification">
      <div style="width: 400px;">
        <a-form
            ref="formRefReport"
            :label-col="labelCol"
            :model="formStateReport"
            :rules="rules"
            :wrapper-col="wrapperCol"
        >
          <a-form-item label="举报要求">
                    <span
                        style="display: block;width: 400px"
                    >
                      要求真实，并且上传相关举报的图片，文字，视频佐证材料等。
                    </span>
          </a-form-item>
          <a-form-item ref="reportObject"
                       label="投诉类型"
                       name="reportObject"
          >
            <a-select v-model:value="formStateReport.reportObject">
              <a-select-option value="投诉岗位">投诉岗位</a-select-option>
              <a-select-option value="投诉企业">投诉企业</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item ref="reportContact" label="联系电话" name="reportContact">
            <a-input v-model:value="formStateReport.reportContact"/>
          </a-form-item>
          <a-form-item label="举报描述" name="reportDescribe">
            <a-textarea v-model:value="formStateReport.reportDescribe"
                        :auto-size="{minRows: 2, maxRows: 10}"
                        :maxlength="300"
                        show-count
                        style="width: 300px"/>
          </a-form-item>
          <a-form-item label="佐证材料" name="reportFileList">
            <a-upload-dragger
                v-model:fileList="fileListReport"
                :multiple="true"
                action="http://localhost:8080/file/upload"
                name="file"
                style="width: 400px"
                @change="handleChangeReport"
                @remove="handleRemove"
            >
              <p class="ant-upload-drag-icon">
                <inbox-outlined></inbox-outlined>
              </p>
              <p class="ant-upload-text">单击或拖动文件到此区域上传</p>
              <p class="ant-upload-hint">
                支持单次或批量上传!
              </p>
            </a-upload-dragger>


          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>


  <div class="jobAndEmployerDetail">
    <div class="top">
      <a-page-header
          sub-title="岗位详情表单"
          title="返回"
          @back="() => $router.go(-1)"
      />
      <a-button danger style="float: right;" @click="showModalVerification">举报</a-button>
    </div>
    <div class="bottom">
      <a-divider orientation="left" style="color:#4D7181; font-size: 20px;">职位信息</a-divider>
      <a-descriptions :title="formState.jobTitle">
        <a-descriptions-item label="类型">{{ formState.jobType }}</a-descriptions-item>
        <a-descriptions-item label="薪资">{{ formState.jobSalary }} / {{ formState.jobSalaryType }}
        </a-descriptions-item>
        <a-descriptions-item label="地点">{{ formState.jobLocation }}</a-descriptions-item>
        <a-descriptions-item :span="3" label="工作时间">
          {{ formState.jobWorkingHours }}
        </a-descriptions-item>
        <a-descriptions-item :span="3" label="招聘周期">
          {{ formState.jobGiveStartDate }} -- {{ formState.jobGiveEndDate }}
        </a-descriptions-item>
        <a-descriptions-item :span="3" label="工作周期">
          {{ formState.jobStartDate }} -- {{ formState.jobEndDate }}
        </a-descriptions-item>

        <a-descriptions-item :span="3" label="职位描述">
          {{ formState.jobDescription }}
        </a-descriptions-item>
        <a-descriptions-item :span="3" label="职位要求">
          {{ formState.jobRequirements }}
        </a-descriptions-item>
      </a-descriptions>


      <a-divider orientation="left" style="color:#4D7181; font-size: 20px;">公司信息</a-divider>
      <a-badge-ribbon :color="Color(formState.employerIsVerified)" :text="formState.employerIsVerified">
        <div style="display: flex;padding-top: 30px">
          <div>
            <a-descriptions :title="formState.employerCompanyName">
              <a-descriptions-item label="公司行业">{{ formState.employerCompanyIndustry }}</a-descriptions-item>
              <a-descriptions-item :span="2" label="公司官网">
                {{ formState.employerCompanyWebsite }}
              </a-descriptions-item>
              <a-descriptions-item :span="3" label="公司简介">
                {{ formState.employerCompanyDescription }}
              </a-descriptions-item>

              <a-descriptions-item :span="3" label="公司地址">
                {{ formState.employerCompanyAddress }}
              </a-descriptions-item>
            </a-descriptions>
          </div>
          <div>
            <a-avatar
                :size="150"
                :src="'http://localhost:8080/image/download?name=' + formState.userAvatarUrl"
            />
          </div>
        </div>

      </a-badge-ribbon>
    </div>
    <div style="display: flex;justify-content: space-between;padding: 10px">
      <div style="width: 40%;display: flex;justify-content: space-around;">
        <a-button v-if="!jobIsCollect" ghost style="width: 48%" type="primary" @click="collect(formState.jobId,'job')">
          收藏岗位
        </a-button>

        <a-button v-else danger ghost style="width: 48%" type="primary" @click="cancelCollect(formState.jobId,'job')">
          取消收藏岗位
        </a-button>

        <a-button v-if="!employerIsCollect" ghost style="width: 48%" type="primary"
                  @click="collect(formState.jobEmployerId,'employer')">收藏公司
        </a-button>

        <a-button v-else danger ghost style="width: 48%" type="primary"
                  @click="cancelCollect(formState.jobEmployerId,'employer')">取消收藏公司
        </a-button>
      </div>


      <a-button v-if="!jobIsSend" ghost style="width: 30%" type="primary" @click="sendJob">投递一下</a-button>
      <a-button v-else danger ghost style="width: 30%" type="primary" @click="cancelSendJob">撤回投递</a-button>
    </div>

  </div>
</template>

<style scoped>
.jobAndEmployerDetail {
  width: 100%;
  height: 100%;


  .top {
    border-bottom: 1px solid #ccc;
    border-radius: 10px;
    padding-right: 20px;
  }

  .bottom {
    padding: 10px 50px 50px;
  }
}


</style>
